import axios from 'axios';
import moment from 'moment';

// 1. 初始状态.
const state = () => ({
    memoryUsed: [],
    memoryUsages: [
        {
            item: '已使用内存',
            percent: 0,
        },
        {
            item: '未使用内存',
            percent: 0,
        },
    ],
    cpuUsages: [
        {
            item: '已使用CPU',
            percent: 0,
        },
        {
            item: '未使用CPU',
            percent: 0,
        },
    ],
    gcCounts: [],
});

// 2. 计算属性.
const getters = {};

// 3. 异步修改.
const actions = {
    loadMetrics({ state }, iid) {
        return axios.all([
            axios.get(`/jvm/memoryUsage/${iid}`),
            axios.get(`/jvm/memoryUsageRate/${iid}`),
            axios.get(`/jvm/cpuUsageRate/${iid}`),
            axios.get(`/jvm/getGCDetail/${iid}`),
        ]).then(axios.spread((usage, memory, cpu, gc) => {
            const {
                committed,
                max,
                timeline,
                used,
            } = usage.data;
            const timestamp = moment(timeline * 1000).format('HH:mm:ss');

            state.memoryUsed.push({
                item: 'committed',
                time: timestamp,
                usage: committed,
            });
            state.memoryUsed.push({
                item: 'max',
                time: timestamp,
                usage: max,
            });
            state.memoryUsed.push({
                item: 'used',
                time: timestamp,
                usage: used,
            });

            state.memoryUsages[0].percent = Number.parseFloat(memory.data.usedRate.toFixed(2));
            state.memoryUsages[1].percent = Number.parseFloat(memory.data.unusedRate.toFixed(2));

            state.cpuUsages[0].percent = Number.parseFloat(cpu.data.usedRate.toFixed(2));
            state.cpuUsages[1].percent = Number.parseFloat(cpu.data.unusedRate.toFixed(2));

            Object.entries(gc.data).forEach((item) => {
                state.gcCounts.push({
                    item: item[0],
                    time: timestamp,
                    count: item[1],
                });
            });
        }));
    },
};

// 4. 同步修改.
const mutations = {
    clearData(state) {
        state.memoryUsed = [];
        state.gcCounts = [];
    },
};

// 5. 模块导出.
export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations,
};
